import React from "react";
import PropTypes from "prop-types";
import {
  Layout,
  Menu,
  Icon,
  Avatar,
  Dropdown,
  message /* Tag, message */
} from "antd";
import DocumentTitle from "react-document-title";
import { connect } from "dva";
import { Link, Route, Redirect, Switch } from "dva/router";
import moment from "moment";
/* import groupBy from "lodash/groupBy";
 */ import { ContainerQuery } from "react-container-query";
import classNames from "classnames";
import Debounce from "lodash-decorators/debounce";
/* import HeaderSearch from "../components/HeaderSearch";
 */ import NoticeIcon from "../components/NoticeIcon";
import GlobalFooter from "../components/GlobalFooter";
import NotFound from "../routes/Exception/404";
import styles from "./BasicLayout.less";
import IconS from "../components/IconS";
import {
  systemComVaseInfoGet,
  systemOauthGetUserMenus,
  systemPerAccountInfoGetUserAccount,
  updateSelectMessageRead //设置所有未读消息为已读（new）
} from "../services/api";
import MessageDetail from "../routes/Administrative/MessageSettings/messageDetail";

const store = require("store");

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;
const menugroup = {
  0: ["企业首页", "企业通讯录", "企业管理"],
  1: ["人事管理", "考勤管理", "医社保管理", "奖惩管理"],
  2: ["消息", "审批", "劳务薪酬", "设备管理", "合同管理"],
  3: ["活动管理", "项目管理", "任务管理", "申报业务"],
  4: ["课件管理(培训机构)", "培训管理(培训机构)", "培训管理(参训单位)"],
  5: ["企业保险"],
  6: [
    "地图可视化",
    "活动统计",
    "项目统计",
    "任务统计",
    "审批统计",
    "考勤统计",
    "培训统计",
    "保险统计"
  ],
  7: ["仪表盘", "表单页", "列表页", "详情页", "结果", "异常"]
};
const topMenu = [
  {
    to: "/HomePage/Initialization",
    text: "",
    items: ["企业首页", "企业通讯录", "企业管理"]
  },
  {
    to: "/PersonnelRecruitment/ListContainer",
    text: "人事",
    items: ["人事管理", "考勤管理", "医社保管理", "奖惩管理"]
  },
  {
    to: "/xiaoxitongzhi/Messages",
    text: "行政",
    items: ["消息", "审批", "劳务薪酬", "设备管理", "合同管理"]
  },
  {
    to: "/taskmanager/tasklist",
    text: "业务",
    items: ["活动管理", "项目管理", "任务管理", "申报业务"]
  },
  {
    to: "/TrainingUnitsTrainingManagement/CoursesList",
    text: "培训",
    items: ["课件管理(培训机构)", "培训管理(培训机构)", "培训管理(参训单位)"]
  },
  {
    to: "/insurancemanagement/enterpriseinsurance",
    text: "金融保险",
    items: ["企业保险"]
  },
  {
    to: "/exception/404",
    text: "统计",
    items: [
      "地图可视化",
      "活动统计",
      "项目统计",
      "任务统计",
      "审批统计",
      "考勤统计",
      "培训统计",
      "保险统计"
    ]
  }
];

const query = {
  "screen-xs": {
    maxWidth: 575
  },
  "screen-sm": {
    minWidth: 576,
    maxWidth: 767
  },
  "screen-md": {
    minWidth: 768,
    maxWidth: 991
  },
  "screen-lg": {
    minWidth: 992,
    maxWidth: 1199
  },
  "screen-xl": {
    minWidth: 1200
  }
};

/**
通知头像
01开头：系统通知
02开头：任务通知
03开头：企业通知
04开头：考试通知
05开头：公安通知
06开头：平台通知 */
const noticeAwars = {
  "01": (
    <IconS
      style={{ fontSize: 34, color: "#A3DEDE" }}
      type="xitongxinxi saas2"
    />
  ),
  "02": (
    <IconS
      style={{ fontSize: 34, color: "#9CE6C3" }}
      type="renwutongzhiicon- saas2"
    />
  ),
  "03": (
    <IconS style={{ fontSize: 34, color: "#FFCE3C" }} type="qiyexinxi saas2" />
  ),
  "04": (
    <IconS
      style={{ fontSize: 34, color: "#C9A3DE" }}
      type="kaoshiicon- saas2"
    />
  ),
  "05": (
    <IconS
      style={{ fontSize: 34, color: "#0F71FF" }}
      type="gonganbuxinxi saas2"
    />
  ),
  "06": (
    <IconS
      style={{ fontSize: 34, color: "#B7D4FF" }}
      type="renyuanfasongxinxi saas2"
    />
  )
};

const refresh = {
  HomePage: 0,
  Organization: 0,
  enterprise: 0,
  PersonnelRecruitment: 1,
  attendancemanagement: 1,
  medical: 1,
  insurancemanagement: 5,
  xiaoxitongzhi: 2,
  examinationapproval: 2,
  LaborCompensation: 2,
  devicesManagement: 2,
  TrainingUnitsTrainingManagement: 4,
  contractManagement: 2,
  taskmanager: 3,
  dashboard: 7
};

class BasicLayout extends React.PureComponent {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object
  };
  constructor(props) {
    super(props);
    // 把一级 Layout 的 children 作为菜单项
    this.menus = props.navData.reduce(
      (arr, current) => arr.concat(current.children),
      []
    );
    const currentGroup =
      refresh[this.props.location.pathname.split("/")[1]] || 0;
    this.state = {
      menuauth: [], //后台返回的菜单
      openKeys: this.getDefaultCollapsedSubMenus(props),
      currentGroup, //当前组
      topMenu,
      record: {},
      checkModal: false
    };
    this.loginOut();
    console.log(store.get("saas"), "constructor");
    this.systemComVaseInfoGet();
    if (store.get("saas") !== undefined) {
      this.systemComVaseInfoGet();
      this.systemOauthGetUserMenus();
      this.systemPerAccountInfoGetUserAccount();
      this.props.dispatch({
        type: "global/fetchNotices"
      });
    }
  }
  systemComVaseInfoGet = () => {
    systemComVaseInfoGet({}).then(
      response => {
        console.log(response, "systemComVaseInfoGet-response-获取企业详情");
        const topMenu1 = this.state.topMenu;
        topMenu1[0].text = response.data.comName;
        this.props.dispatch({
          type: "global/companyInfo",
          payload: response.data,
          topMenu: [...topMenu1]
        });
      },
      err => {
        console.log(err, "systemComVaseInfoGet-err-获取企业详情");
      }
    );
  };

  //获取用户登陆菜单
  systemOauthGetUserMenus = () => {
    if (store.get("saas") !== undefined) {
      systemOauthGetUserMenus({}).then(
        response => {
          console.log(
            response,
            "systemOauthGetUserMenus-response-获取用户登陆菜单"
          );
          const menuauth = [];
          response.data.forEach(val => {
            if (val.menuId && val.menuId === "50010001") {
              store.set("coursesListURL", { coursesListURL: val.menuUrl });
            } else if (val.menuId && val.menuId === "50010002") {
              store.set("orderManagementURL", {
                orderManagementURL: val.menuUrl
              });
            } else if (val.menuId && val.menuId === "50010003") {
              store.set("studentManagementURL", {
                studentManagementURL: val.menuUrl
              });
            } else if (val.menuId && val.menuId === "80010001") {
              store.set("coursewareLibraryManagementURL", {
                coursewareLibraryManagementURL: val.menuUrl
              });
            } else if (val.menuId && val.menuId === "80020001") {
              store.set("orderManagementOtherURL", {
                orderManagementOtherURL: val.menuUrl
              });
            } else if (val.menuId && val.menuId === "80020002") {
              store.set("studentManagementOtherURL", {
                studentManagementOtherURL: val.menuUrl
              });
            } else if (val.menuId && val.menuId === "80020003") {
              store.set("classManagementURL", {
                classManagementURL: val.menuUrl
              });
            }

            menuauth.push(val.menuName);
          });
          this.setState({ menuauth });
        },
        err => {
          console.log(err, "systemOauthGetUserMenus-err-获取用户登陆菜单");
        }
      );
    }
  };
  //获取当前登陆用户账号信息
  systemPerAccountInfoGetUserAccount = () => {
    if (store.get("saas") !== undefined) {
      systemPerAccountInfoGetUserAccount({}).then(
        response => {
          console.log(
            response,
            "systemPerAccountInfoGetUserAccount-response-获取当前登陆用户账号信息"
          );
          this.props.dispatch({
            type: "user/fetchCurrent",
            payload: response.data
          });
        },
        err => {
          console.log(
            err,
            "systemPerAccountInfoGetUserAccount-err-获取当前登陆用户账号信息"
          );
        }
      );
    }
  };

  getChildContext() {
    const { location, navData, getRouteData } = this.props;
    const routeData = getRouteData("BasicLayout");
    const firstMenuData = navData.reduce(
      (arr, current) => arr.concat(current.children),
      []
    );
    const menuData = this.getMenuData(firstMenuData, "");
    const breadcrumbNameMap = {};

    routeData.concat(menuData).forEach(item => {
      breadcrumbNameMap[item.path] = {
        name: item.name,
        component: item.component
      };
    });
    return { location, breadcrumbNameMap };
  }
  componentDidMount() {}

  componentWillUpdate() {
    this.loginOut();
  }

  componentWillUnmount() {
    this.triggerResizeEvent.cancel();
  }

  onCollapse = collapsed => {
    this.props.dispatch({
      type: "global/changeLayoutCollapsed",
      payload: collapsed
    });
  };
  onMenuClick = ({ key }) => {
    if (key === "logout") {
      store.clearAll();
      this.props.dispatch({
        type: "login/logout"
      });
    }
  };
  getMenuData = (data, parentPath) => {
    let arr = [];
    data.forEach(item => {
      if (item.children) {
        arr.push({ path: `${parentPath}/${item.path}`, name: item.name });
        arr = arr.concat(
          this.getMenuData(item.children, `${parentPath}/${item.path}`)
        );
      }
    });
    return arr;
  };
  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
    currentMenuSelectedKeys.splice(-1, 1);
    if (currentMenuSelectedKeys.length === 0) {
      return ["dashboard"];
    }
    return currentMenuSelectedKeys;
  }
  getCurrentMenuSelectedKeys(props) {
    const {
      location: { pathname }
    } =
      props || this.props;
    const keys = pathname.split("/").slice(1);
    if (keys.length === 1 && keys[0] === "") {
      return [this.menus[0].key];
    }
    return keys;
  }
  getNavMenuItems(menus, parentPath = "") {
    if (!menus) {
      return [];
    }
    let menusData = menus;
    if (!parentPath) {
      menusData = menus.filter(val => {
        return menugroup[this.state.currentGroup].indexOf(val.name) !== -1;
      });
    }
    return menusData.map(item => {
      //console.log(item.name, "item.name");
      if (this.state.menuauth.indexOf(item.name) === -1) {
        return null;
      }
      if (!item.name) {
        return null;
      }
      let itemPath;
      if (item.path.indexOf("http") === 0) {
        itemPath = item.path;
      } else {
        itemPath = `${parentPath}/${item.path || ""}`.replace(/\/+/g, "/");
      }
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
              item.icon ? (
                <span>
                  <IconS type={item.icon} />
                  <span>{item.name}</span>
                </span>
              ) : (
                item.name
              )
            }
            key={item.key || item.path}
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
      const icon = item.icon && <IconS type={item.icon} />;
      return (
        <Menu.Item key={item.key || item.path}>
          {/^https?:\/\//.test(itemPath) ? (
            <a href={itemPath} target={item.target}>
              {icon}
              <span>{item.name}</span>
            </a>
          ) : (
            <Link
              to={itemPath}
              target={item.target}
              replace={itemPath === this.props.location.pathname}
            >
              {icon}
              <span>{item.name}</span>
            </Link>
          )}
        </Menu.Item>
      );
    });
  }
  getPageTitle() {
    const { location, getRouteData } = this.props;
    const { pathname } = location;
    let title = "sass系统";
    getRouteData("BasicLayout").forEach(item => {
      if (item.path === pathname) {
        title = `${item.name}`;
      }
    });
    return title;
  }
  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return [];
    }

    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      newNotice.avatar = noticeAwars[newNotice.messageType.substr(0, 2)];
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      // transform id to item key
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      return newNotice;
    });
    return newNotices;
  }

  loginOut = () => {
    if (store.get("saas") === undefined) {
      this.props.dispatch({
        type: "login/logout"
      });
    }
  };

  mainmenu = key => {
    this.setState({
      currentGroup: key
    });
    setTimeout(() => {
      this.setState({
        openKeys: this.getDefaultCollapsedSubMenus(this.props)
      });
    }, 10);
  };

  handleOpenChange = openKeys => {
    const lastOpenKey = openKeys[openKeys.length - 1];
    const isMainMenu = this.menus.some(
      item =>
        lastOpenKey && (item.key === lastOpenKey || item.path === lastOpenKey)
    );
    this.setState({
      openKeys: isMainMenu ? [lastOpenKey] : [...openKeys]
    });
  };
  toggle = () => {
    const { collapsed } = this.props;
    this.props.dispatch({
      type: "global/changeLayoutCollapsed",
      payload: !collapsed
    });
    this.triggerResizeEvent();
  };

  @Debounce(600)
  triggerResizeEvent() {
    // eslint-disable-line
    const event = document.createEvent("HTMLEvents");
    event.initEvent("resize", true, false);
    window.dispatchEvent(event);
  }
  //原来的清空改成查看所有通知
  handleSearchFor = () => {
    console.log(this.props, "this.props");
    this.props.history.replace("/xiaoxitongzhi/Messages");
  };
  //设置所有未读消息为已读（new）s
  handleReadAll = () => {
    const keyId = this.props.notices.map(val => val.id);
    updateSelectMessageRead({
      ids: keyId.join(",")
    })
      .then(data => {
        console.log("设置为已读", data);
        this.props.dispatch({
          type: "global/fetchNotices"
        });
      })
      .catch(err => {
        console.log("设置为已读失败", err);
        message.warning("设置为已读失败！" + err);
      });
  };
  handleNoticeVisibleChange = visible => {
    if (visible) {
      this.props.dispatch({
        type: "global/fetchNotices"
      });
    }
  };
  render() {
    const {
      currentUser,
      collapsed,
      fetchingNotices,
      getRouteData
    } = this.props;

    const menu = (
      <Menu
        className={styles.menu}
        selectedKeys={[]}
        onClick={this.onMenuClick}
      >
        <Menu.Item disabled>
          <Icon type="user" />个人中心
        </Menu.Item>
        <Menu.Item disabled>
          <Icon type="setting" />设置
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />退出登录
        </Menu.Item>
      </Menu>
    );
    const noticeData = this.getNoticeData();
    // Don't show popup menu when it is been collapsed
    const menuProps = collapsed
      ? {}
      : {
          openKeys: this.state.openKeys
        };
    const layout = (
      <Layout>
        <Header className={styles.header}>
          <div className={styles.logo}>
            <IconS type="logo-" />
            <h1>
              {this.state.topMenu.map((val, index) => {
                if (index === 0) {
                  return (
                    <Link
                      key={val.to + index}
                      onClick={() => {
                        this.mainmenu(index);
                      }}
                      to={val.to}
                      replace={val.to === this.props.location.pathname}
                    >
                      {this.props.companyInfo.comName || this.state.topMenu[0].text}
                    </Link>
                  );
                } else {
                  return "";
                }
              })}
            </h1>
          </div>
          <div className={styles.topmenu}>
            {this.state.topMenu.map((val, index) => {
              if (this.state.menuauth.indexOf(val.text) === -1) {
                return null;
              }
              if (index === 0) {
                return "";
              }
              return (
                <Link
                  key={val.to + index}
                  onClick={() => {
                    this.mainmenu(index);
                  }}
                  className={
                    this.state.currentGroup === index ? "selected" : ""
                  }
                  to={val.to}
                  replace={val.to === this.props.location.pathname}
                >
                  {val.text}
                </Link>
              );
            })}
          </div>

          <div className={styles.right}>
            {/* <HeaderSearch
              className={`${styles.action} ${styles.search}`}
              placeholder="站内搜索"
              dataSource={["搜索提示一", "搜索提示二", "搜索提示三"]}
              onSearch={value => {
                console.log("input", value); // eslint-disable-line
              }}
              onPressEnter={value => {
                console.log("enter", value); // eslint-disable-line
              }}
            /> */}
            <NoticeIcon
              className={styles.action}
              count={noticeData.length}
              onItemClick={(item /* tabProps */) => {
                //this.props.history.replace();
                //console.log(item, tabProps); // eslint-disable-line1
                this.setState({ record: item, checkModal: true });
              }}
              searchFor={this.handleSearchFor}
              readAll={this.handleReadAll}
              onPopupVisibleChange={this.handleNoticeVisibleChange}
              loading={fetchingNotices}
              popupAlign={{ offset: [20, -16] }}
              /* popupVisible */
            >
              <NoticeIcon.Tab
                list={noticeData}
                title="通知"
                emptyText="无未读通知"
                emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
              />
              {/* <NoticeIcon.Tab
                list={noticeData["消息"]}
                title="消息"
                emptyText="您已读完所有消息"
                emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
              />
              <NoticeIcon.Tab
                list={noticeData["待办"]}
                title="待办"
                emptyText="你已完成所有待办"
                emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
              /> */}
            </NoticeIcon>
            {/*             {currentUser.name ? (
 */}
            <Dropdown overlay={menu}>
              <span className={`${styles.action} ${styles.account}`}>
                <Avatar
                  size="biger"
                  className={styles.avatar}
                  src={currentUser.avatar}
                />
                {currentUser.name}
              </span>
            </Dropdown>
            {/*   ) : (
              <Spin size="small" style={{ marginLeft: 8 }} />
            )}  */}
          </div>
        </Header>
        <Layout>
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            breakpoint="md"
            onCollapse={this.onCollapse}
            width={254}
            className={styles.sider}
          >
            <Icon
              className={styles.trigger}
              type={collapsed ? "menu-unfold" : "menu-fold"}
              onClick={this.toggle}
            />
            <Menu
              className="sidemenu"
              theme="light"
              mode="inline"
              {...menuProps}
              onOpenChange={this.handleOpenChange}
              selectedKeys={this.getCurrentMenuSelectedKeys()}
              style={{ margin: "16px 0", width: "100%" }}
            >
              {this.getNavMenuItems(this.menus)}
            </Menu>
          </Sider>
          <Content
            className={`layout-content${
              this.getDefaultCollapsedSubMenus(this.props)[0]
            }`}
          >
            <Switch>
              {getRouteData("BasicLayout").map(item => (
                <Route
                  exact={item.exact}
                  key={item.path}
                  path={item.path}
                  component={item.component}
                />
              ))}
              <Redirect exact from="/" to="/HomePage/Initialization" />
              <Route component={NotFound} />
            </Switch>
            <GlobalFooter
              copyright={
                <div>
                  Copyright <Icon type="copyright" /> {new Date().getFullYear()}
                  百川信（厦门）网络信息服务有限公司
                </div>
              }
            />
          </Content>
        </Layout>
        <MessageDetail
          record={this.state.record}
          visible={this.state.checkModal}
          closeModal={() => {
            this.setState({ checkModal: false });
          }}
        />
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
      </DocumentTitle>
    );
  }
}

export default connect(state => ({
  currentUser: state.user.currentUser,
  collapsed: state.global.collapsed,
  fetchingNotices: state.global.fetchingNotices,
  notices: state.global.notices,
  companyInfo: state.global.companyInfo
}))(BasicLayout);
